package com.yingxin.yxerp.module.organization.service.helper;

import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.organization.entity.Department;
import com.yingxin.yxerp.module.organization.entity.constant.DeptType;
import com.yingxin.yxerp.module.organization.vo.resp.DepartmentRespVo;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * 部门树结构工具类
 */
public class DepartmentTreeHelper {

    /**
     * 构建树
     */
    public static List<DepartmentRespVo> build(List<DepartmentRespVo> departments) {
        DepartmentRespVo headquarters = null;
        // 总部
        for (DepartmentRespVo department : departments) {
            if (DeptType.HEADQUARTERS.equals(department.getId())) {
                headquarters = department;
                break;
            }
        }

        if (headquarters == null) {
            throw new BizException("部门数据异常");
        }
        List<DepartmentRespVo> rootTree = new ArrayList<>();
        rootTree.add(headquarters);

        int a = 0;
        List<DepartmentRespVo> secondLevelTree = new ArrayList<>();
        for (DepartmentRespVo department : departments) {
            if (headquarters.getId().equals(department.getParentId())) {
                a = a + findChild(department, departments);
                secondLevelTree.add(department);
            }
        }
        int b = headquarters.getDirectStaffCount();
        headquarters.setStaffCount(a + b);
        headquarters.setChildren(secondLevelTree);
        return rootTree;
    }

    /**
     * 递归查找子级
     */
    private static int findChild(DepartmentRespVo parent, List<DepartmentRespVo> departments) {
        int a = 0;
        for (DepartmentRespVo department : departments) {
            if (null != department.getParentId() && department.getParentId().equals(parent.getId())) {
                a = a + findChild(department, departments);
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(department);
            }
        }

        int b = parent.getDirectStaffCount();
        parent.setStaffCount(a + b);
        return parent.getStaffCount();
    }

    /**
     * 递归查找父级
     */
    public static List<String> findParent(List<String> idList, String pid, List<Department> departmentList) {
        if (StringUtils.isNotEmpty(pid)) {
            Department dept = null;
            for (Department d : departmentList) {
                if (pid.equals(d.getId())) {
                    dept = d;
                    break;
                }
            }
            if (dept != null) {
                idList.add(dept.getId());
                if (!DeptType.HEADQUARTERS.equals(dept.getId())) {
                    findParent(idList, dept.getParentId(), departmentList);
                }
            }
        }
        return idList;
    }

}